package com.huibao.hulibao.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.PersistableBundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.apkfuns.logutils.LogUtils;
import com.huibao.hulibao.R;
import com.huibao.hulibao.constant.GlobalConstants;
import com.huibao.hulibao.fragment.CustomerManagerWebViewFragmentView;
import com.huibao.hulibao.fragment.HuliFragmentView;
import com.huibao.hulibao.fragment.LocationFragmentView;
import com.huibao.hulibao.fragment.MessageFragmentView;
import com.huibao.hulibao.fragment.MoreFragmentView;
import com.huibao.hulibao.fragment.ServerFragmentView;
import com.huibao.hulibao.utils.AppManager;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import pdautils.PdaPrint;

import com.huibao.hulibao.utils.DialogUtils;
import com.huibao.hulibao.utils.MyUtils;
import com.huibao.hulibao.utils.PreUtils;
import com.huibao.hulibao.utils.T;

public class MainActivity extends BaseActivity {

    private long mExitTime;
    private int mIndex;
    public Fragment[] mFragments;

    @BindView(R.id.rg_group)
    RadioGroup rg;
    @BindView(R.id.fl_content)
    FrameLayout fl_content;
    @BindView(R.id.rb_location)
    RadioButton rb_location;
    @BindView(R.id.rb_huli)
    RadioButton rb_huli;

    // 网络请求加载对话框
    private Dialog myDialog;

    ServerFragmentView serverfv;
    MessageFragmentView msgfv;
    HuliFragmentView hlfv;
    // LocationFragmentView lfv;
    MoreFragmentView morefv;
    CustomerManagerWebViewFragmentView customerManagerWebViewFragmentView;


    public Handler ServerHandler = new Handler();
    public Handler MessageHandler = new Handler();
    // 推送传来的json
    public String web_json = "";

    // 点击事件
    @OnClick({R.id.rb_server, R.id.rb_msg, R.id.rb_huli, R.id.rb_location, R.id.rb_more})
    public void onClick(View view) {
//        FragmentManager fragmentManager = getSupportFragmentManager();
//        FragmentTransaction transaction = fragmentManager.beginTransaction();
        switch (view.getId()) {

            case R.id.rb_msg:
//                transaction.replace(R.id.fl_content, msgfv);
//                transaction.commit();
                setIndexSelected(0);
                msgfv.autoRefresh();
                serverfv.stopRefresh();
                break;

            case R.id.rb_location:
//                transaction.replace(R.id.fl_content, lfv);
//                transaction.commit();
                setIndexSelected(1);
                serverfv.stopRefresh();
                msgfv.stopRefresh();
                break;

            case R.id.rb_server:
//                transaction.replace(R.id.fl_content, serverfv);
//                transaction.commit();
                setIndexSelected(2);
                serverfv.autoRefresh();
                msgfv.stopRefresh();
                break;
            case R.id.rb_huli:
//                transaction.replace(R.id.fl_content, hlfv);
//                transaction.commit();
                setIndexSelected(3);
                serverfv.stopRefresh();
                msgfv.stopRefresh();
                break;

            case R.id.rb_more:
                setIndexSelected(4);
                serverfv.stopRefresh();
                msgfv.stopRefresh();
//                transaction.replace(R.id.fl_content, morefv);
//                transaction.commit();
                break;
        }
    }

    public void showDialog() {
        myDialog = DialogUtils.createLoadingDialog(MainActivity.this, getResources().getString(R.string.jiazaizhong));
    }

    public void closeDialog() {
        DialogUtils.closeDialog(myDialog);
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        // 解决重影问题
        // super.onSaveInstanceState(outState, outPersistentState);
    }

//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        LogUtils.d("resultCode = " + requestCode);
//    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        // 显示指定的系统
        String sysType = (String) PreUtils.getObject(getApplicationContext(), "SysType");
        LogUtils.d("sysType = " + sysType);
        if (sysType != null && sysType.equals("ck")) {
            rb_huli.setVisibility(View.GONE);
        }

        initFragments();
        bindService();

        // 是否跳转到web护理完成后的
        if (getIntent().getBooleanExtra("jumpWeb", false)) {
            String jumpUrl = getIntent().getStringExtra("jumpUrl");
            Intent intent = new Intent(this, WebViewActivity.class);
            intent.putExtra("url", jumpUrl);
            startActivity(intent);
        }
    }

    // 初始化5个页面
    public void initFragments() {

        msgfv = new MessageFragmentView();
        customerManagerWebViewFragmentView = new CustomerManagerWebViewFragmentView();
        // lfv = new LocationFragmentView();
        serverfv = new ServerFragmentView();
        hlfv = new HuliFragmentView();
        morefv = new MoreFragmentView();
        mFragments = new Fragment[]{msgfv, customerManagerWebViewFragmentView, serverfv, hlfv, morefv};
        FragmentTransaction ft =
                getSupportFragmentManager().beginTransaction();
        ft.add(R.id.fl_content, msgfv).commit();
        Intent intent = getIntent();
        // 获取推送需要显示的fragment的下标
        int position = intent.getIntExtra("position", 0);
        // 获取推送的web_json
        web_json = intent.getStringExtra("web");
        if (position == 1) {
            setIndexSelected(1);
            rg.check(R.id.rb_location);
        } else if (position == 2) {
            setIndexSelected(0);
            rg.check(R.id.rb_msg);
        } else if (position == 3) {
            setIndexSelected(4);
            rg.check(R.id.rb_more);
        } else {
            setIndexSelected(0);
            rg.check(R.id.rb_msg);
        }
    }


    // 设置显示指定的fragment
    public void setIndexSelected(int index) {
        if (mIndex == index) {
            return;
        }
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction ft = fragmentManager.beginTransaction();
        //隐藏
        ft.hide(mFragments[mIndex]);

        //判断是否添加
        if (!mFragments[index].isAdded()) {
            ft.add(R.id.fl_content, mFragments[index]).show(mFragments[index]);
        } else {
            ft.show(mFragments[index]);
        }
        // 异步防止频繁操作崩溃
        fragmentManager.executePendingTransactions();
        ft.commit();
        //再次赋值
        mIndex = index;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            unbindService();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }

        ServerHandler = null;
        MessageHandler = null;
    }

    public void bindService() {
        //com.zkc.aidl.all为远程服务的名称，不可更改
        //com.smartdevice.aidl为远程服务声明所在的包名，不可更改，
        // 对应的项目所导入的AIDL文件也应该在该包名下
        Intent intent = new Intent("com.zkc.aidl.all");
        intent.setPackage("com.smartdevice.aidl");
        bindService(intent, PdaPrint.getInstance().mServiceConn, Context.BIND_AUTO_CREATE);
    }

    public void unbindService() {
        unbindService(PdaPrint.getInstance().mServiceConn);
    }

    // APP退出管理
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (rb_location.isChecked()) {
                    if (customerManagerWebViewFragmentView.wb_detail.canGoBack()) {
                        customerManagerWebViewFragmentView.wb_detail.goBack();// 返回前一个页面
                    } else {
                        if ((System.currentTimeMillis() - mExitTime) > 2000) {
                            T.showShort(getApplicationContext(), getString(R.string.tuichuchengxu));
                            mExitTime = System.currentTimeMillis();
                        } else {
                            AppManager.getAppManager().AppExit(this);
                            finish();
                        }
                    }
                } else {
                    if ((System.currentTimeMillis() - mExitTime) > 2000) {
                        T.showShort(getApplicationContext(), getString(R.string.tuichuchengxu));
                        mExitTime = System.currentTimeMillis();
                    } else {
                        AppManager.getAppManager().AppExit(this);
                        finish();
                    }
                }


                break;
            default:
                return super.onKeyDown(keyCode, event);
        }
        return true;
    }
}
